<script>
	import md5Libs from "uview-ui/libs/function/md5";
	// #ifdef APP-PLUS
	var StepCounter = uni.requireNativePlugin('YStep-Counter');
	// #endif
	var that;
	export default {

		onLaunch: async function() {
			console.log('uview 版本', this.$u.config.v);
			this.initTabBar();
			// #ifdef H5
			if (window.location.hash != '') {
				let search = window.location.search.substring(1);
				try {
					if (search.indexOf('hashpath') != -1) {
						let sea = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g,
							'","').replace(/=/g, '":"') + '"}');
						if (sea.hashpath && sea.code && sea.state) {
							window.location.href = window.location.origin + window.location.pathname + '#' + sea
								.hashpath + '?code=' + sea.code + '&state=' + sea.state
						}
					}
				} catch (e) {
					//TODO handle the exception
				}
			}
			// #endif

			//加载配置
			let res = await this.$api.getConfig();
			if (!res.code) {
				return;
			}
			//主题做缓存
			let theme_key = md5Libs.md5(JSON.stringify(res.data.theme));
			if (!this.vuex_theme.key || this.vuex_theme.key != theme_key) {
				this.$u.vuex('vuex_theme', {
					key: theme_key,
					value: res.data.theme
				});
			}

			this.$u.vuex('vuex_config', res.data);


			// #ifdef APP-PLUS
			/* let tabbar = this.$u.deepClone(this.vuex_config.tabbar);
			if (!tabbar) {
				this.$util.setTabbar(this.vuex_tabbar);
				return;
			}
			let num = 0; */
			/* for (let i in tabbar.list) {
				try {
					let imagepath = await this.$util.getCachedImage(tabbar.list[i].image);
					let selectedImage = await this.$util.getCachedImage(tabbar.list[i].selectedImage);
					tabbar.list[i].image = imagepath;
					tabbar.list[i].selectedImage = selectedImage;
					num = i;
				} catch (e) {
					console.log(e);
				}
			} */
			//更新tabbar配置
			//this.$u.vuex('vuex_config.tabbar.list', tabbar.list);
			/* return;

			//全部下载成功使用服务器的导航，否则启用本地备用导航
			if (parseInt(num) + 1 == tabbar.list.length) {
				this.$util.setTabbar(tabbar);
			} else {
				this.$util.setTabbar(this.vuex_tabbar);
			} */


			//region 初始化(开启保活)

			that = this;
			//检查前2天数据			 
			let time = (new Date()).getTime();


			let today = uni.$u.timeFormat(time, 'yyyy-mm-dd')
			let yesterday = uni.$u.timeFormat(time - 86400 * 1000, 'yyyy-mm-dd')
			let the_day_before_yesterday = uni.$u.timeFormat(time - 86400 * 2000, 'yyyy-mm-dd')
			//昨天
			StepCounter.queryStepByDate(yesterday, function(res) {
				that.updateStep(yesterday, res.numberOfSteps, res.distance)

			});

			//前天
			StepCounter.queryStepByDate(the_day_before_yesterday, function(res) {
				that.updateStep(the_day_before_yesterday, res.numberOfSteps, res.distance)

			});


			if (uni.getSystemInfoSync().platform == 'android') {
				console.log("android");
				var enable = true; //true：需要开启前台服务通知保活 false：不需要前台服务保活通知
				if (enable == true) {
					//检查允许通知和忽略电池优化
					this.checkNotifyAndBattery();
				} else {
					this.initStep(enable);
				}
			}

			//10秒回传一次数据
			/* setInterval(() => {
				// that.queryStepCounter()
				StepCounter.queryStepByDate(today, function(res) {
					console.log(res)
					that.updateStep(today, res.numberOfSteps, res.distance)
				});
			}, 10000) */
			//endregion
			// #endif

			


		},
		created() {
			uni.onLocaleChange(e=>{
				this.initTabBar()
			})

		},
		onShow: function() {
			console.log('App Show');
			/* this.$api.activityStepUpdate({
				day: '2024-09-13',
				step: 3236,
				distance: 126
			}).then(({
				code,
				data: res,
				msg
			}) => {
				if (code) {
					console.log(msg);
				}
			}) */


		},
		onHide: function() {
			console.log('App Hide');
		},
		onLoad() {
			console.log('app load')
		},
		methods: {
			checkNotifyAndBattery() {

				//检查是否允许通知，oppo vivo等部分手机默认不允许通知
				StepCounter.checkNotificationsEnabled(function(enable) {
					if (enable) {
						//是否忽略电池优化，vivo部分手机需要忽略电池优化，保活才不被杀掉
						StepCounter.checkIgnoringBatteryOptimizations(function(ret) {
							if (ret == true) {
								that.initStep(true);
							} else {
								//请求忽略电池优化, 由于暂时没有回调通知，只能轮询检查isIgnoringBatteryOptimizations
								StepCounter.requestIgnoreBatteryOptimizations();
							}
						});
					} else {
						//打开通知设置界面
						StepCounter.openNotifySetting();
					}
				});
			},
			initStep(enable) {
				//检查权限
				StepCounter.checkStepPermission(function(res) {
					if (res.result == true) {
						//初始化，确保最先调用
						StepCounter.initStep({
							enable: enable, //是否启用前台服务通知
							contentTitle: "计步器", //标题
							contentText: "正在后台运行" //描述
						});
						/* uni.showToast({
							title: '开始计步啦！'
						}) */
						that.startStepCounter();
					} else {
						uni.showToast({
							title: '运动权限被禁止啦！'
						})
					}
				});
			},
			openAutoStartSetting() {
				//打开后台相关设置(后台活动)，注：此接口不保证所有机型支持，部分机型可能需要去设置允许后台活动
				StepCounter.openAutoStartSetting();
			},
			queryStepCounter() {
				//检查运动传感器权限是否开启

				//查询计步
				StepCounter.queryStepCounter(function(res) {
					console.log(res);
					console.log('queryStepCounter')
					var numberOfSteps = res.numberOfSteps; //当天累计步数
					var distance = res.distance; //当天累计距离
					// that.title = "步数：" + numberOfSteps + "步, 距离：" + distance.toFixed(0) + "米";
				});
			},
			startStepCounter() {
				//检查运动传感器权限是否开启
				var ret = StepCounter.grantedStepPermission();
				console.log(ret);
				if (ret == false) {
					//打开应用设置界面
					StepCounter.openSetting();
					return;
				}

				//开启计步监控
				StepCounter.startStepCounter();
			},
			stopStepCounter() {
				//停止计步监控
				StepCounter.stopStepCounter();
			},
			clearStep() {
				if (uni.getSystemInfoSync().platform == 'android') {
					//计步清零
					StepCounter.clearStep();
				}
			},
			queryStepByDate() {
				//"2022-10-13"
				StepCounter.queryStepByDate("2022-10-24", function(res) {
					console.log(res);
				});
				StepCounter.queryStepByDate("2022-10-25", function(res) {
					console.log(res);
				});
				StepCounter.queryStepByDate("2022-10-26", function(res) {
					console.log(res);
				});
			},
			destroyStep() {
				if (uni.getSystemInfoSync().platform == 'android') {
					//销毁计步器
					StepCounter.destroyStep();
				}
			},
			updateStep(day, step, distance) {
				if (!step) return;

				this.$api.activityStepUpdate({
					day: day,
					step: step,
					distance: distance
				}).then(({
					code,
					data: res,
					msg
				}) => {
					if (code) {
						console.log({
							day,
							step,
							distance
						});
					}
				})
			},
			initTabBar() {
				
				uni.setTabBarItem({
					index: 0,
					text: this.$t('tabbar.step')
				})
				uni.setTabBarItem({
					index: 1,
					text: this.$t('tabbar.activity')
				})
				uni.setTabBarItem({
					index: 2,
					text: this.$t('tabbar.mall')
				})
				uni.setTabBarItem({
					index: 3,
					text: this.$t('tabbar.cart')
				})
				uni.setTabBarItem({
					index: 4,
					text: this.$t('tabbar.my')
				})
			}

		}
	};
</script>

<style lang="scss">
	@import 'uview-ui/index.scss';

	/*每个页面公共css */
	.u-bg-white {
		background-color: #ffffff;
	}

	.u-text-weight {
		font-weight: bold;
	}

	.u-line-height {
		line-height: 50rpx;
	}

	.bg-white {
		background-color: #ffffff;
	}

	.price {
		color: $u-type-error;
	}

	.text-weight {
		font-weight: bold;
	}

	.text-normal {
		font-weight: normal;
	}

	.fa-empty {
		width: 100%;
		flex-direction: column;

		image {
			width: 400rpx;
			height: 400rpx;
		}

		&.top-15 {
			padding-top: 15vh;
		}
	}

	.footer-bar {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 120rpx;
		background-color: #ffffff;
		padding: 0 30rpx;
		z-index: 9999;
	}

	.share-btn {
		padding: 0;
		margin: 0;
		border: 0;
		background-color: transparent;
		line-height: inherit;
		border-radius: 0;
		font-size: inherit;
		color: #999;
	}

	.share-btn::after {
		border: none;
	}

	// #ifdef MP-BAIDU
	.u-radio__icon-wrap,
	.u-checkbox__icon-wrap {
		line-height: 0;
	}

	// #endif
</style>